package com.xyzq.cgate.core.handler;

import com.xyzq.cgate.common.exception.CgateException;
import com.xyzq.cgate.core.plugin.IPlugin;
import com.xyzq.cgate.core.plugin.IPluginChain;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;
import reactor.core.publisher.Mono;
import java.util.List;

/**
 * @Description:
 * @author chenchen
 * @date 2019/6/19 14:32
 */
public class CgateWebHandler implements WebHandler {

    private List<IPlugin> plugins;

    public CgateWebHandler(final List<IPlugin> plugins) {
        this.plugins = plugins;
    }

    @Override
    public Mono<Void> handle(ServerWebExchange exchange) {
        return new DefaultPluginChain(plugins)
                .execute(exchange)
                .doOnError(Throwable::printStackTrace);
    }


    private class DefaultPluginChain implements IPluginChain {

        private int index;

        private final List<IPlugin> plugins;

        public DefaultPluginChain(List<IPlugin> plugins) {
            this.plugins = plugins;
        }

        @Override
        public Mono<Void> execute(ServerWebExchange exchange) {
            if(index < plugins.size()) {
                IPlugin plugin = plugins.get(index++);
                return plugin.execute(exchange, this);
            } else {
                return Mono.empty();
            }
        }
    }
}
